<?php

namespace IDock\Insurance\JTIC\Request;

use IDock\Insurance\JTIC\JTICEnums;
use IDock\Insurance\JTIC\Response\PremiumInquiryResponse;
use IDock\Printer\NonCar\NonCarSubCoveragePrinter;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

class PremiumInquiryRequest extends AllJTICRequest
{
    protected $code = 'V101';

    protected $response = PremiumInquiryResponse::class;

    protected $urlTip = '报价接口';

    /*** @var  PremiumInquiryVisitor $visitor */
    protected $visitor;

    public function generate(): array
    {
        $data = [
            'BasePart' => $this->setBasePart(),
            'Vehicle' => $this->setvehicle(),
            'VehicleOwner' => $this->setVehicleOwner(),
            'ApplicationTCI' => $this->setApplicationTCI(),
            'ApplicationVCI' => $this->setApplicationVCI()
        ];
        if($this->visitor->getNonCarInquiryVisitor()->getNonCarList()){
            $data['ApplicationACC'] = $this->getNonCarList();
            $data['BasePart']['AppAcc'] = '1';
        }
        return $data;
    }

    /**
     * 基础信息
     * @return array
     */
    private function setBasePart(): array
    {
        return [
            'AppTci' => $this->visitor->ciStartData ? '1' : '0',
            'AppVci' => $this->visitor->biStartData ? '1' : '0',
            'AppAcc' => '0',
            'AppProp' => '0',
            'ProdGroup' => $this->visitor->isNewEnergy ? 'A339' : 'A335',
            'DeptTeamCode' => $this->visitor->getExtInfoVisitor()->argc['DeptTeamCode'] ?? '',//出单团队代码
            'SalesCode' => $this->visitor->getExtInfoVisitor()->argc['SalesCode'] ?? '',
            'EmpCode' => $this->visitor->getExtInfoVisitor()->argc['EmpCode'] ?? '',
            'PtlCode' => $this->visitor->getExtInfoVisitor()->argc['PtlCode'] ?? '',
            'BatchCode' => $this->visitor->getExtInfoVisitor()->argc['batchCode'] ?? '',
            'CalcPremiumMode' => '0',
        ];
    }

    /**
     * 车辆信息
     * @return array
     */
    private function setVehicle(): array
    {
        $motorUsageTypeCode = '';
        $motorTypeCode = '';

        JTICEnums::getUsageTypeCode(
            $this->visitor->getVehicleVisitor()->useNatureCode,
            $this->visitor->getVehicleVisitor()->causeType,
            $this->visitor->getVehicleVisitor()->carKindCode,
            $this->visitor->getVehicleVisitor()->vehicleSeat,
            $this->visitor->getVehicleVisitor()->vehicleTonnage,
            $motorUsageTypeCode,
            $motorTypeCode
        );

        return [
            'VehicleId' => $this->visitor->getVehicleVisitor()->vehicleModelCode,
            'ModelCode' => $this->visitor->getExtInfoVisitor()->argc['ModelCode'] ?? '',
            'NoLicenseFlag' => $this->visitor->getVehicleVisitor()->isNewEnergy ? '1' : '0',
            'EcdemicVehicleFlag' => '0',
            'OperateVehicleFlag' => '0',
            'LicensePlateNo' => $this->visitor->getVehicleVisitor()->licenseNo,
            'LicensePlateType' => JTICEnums::$licenseTypeCode[$this->visitor->getVehicleVisitor()->licenseTypeCode] ?? '25',

            'MotorUsageTypeCode' => $motorUsageTypeCode,
            'MotorTypeCode' => $motorTypeCode,
            'TrafficVehicleType' => $this->visitor->getVehicleVisitor()->vehicleStyleCode,

            'VCIChgOwnerFlag' => $this->visitor->getVehicleVisitor()->isTransfer,
            'TCIChgOwnerFlag' => $this->visitor->getVehicleVisitor()->isCiTransfer,
            'TransferDate' => $this->visitor->getVehicleVisitor()->transferDate?date('Ymd',strtotime($this->visitor->getVehicleVisitor()->transferDate)) : '',
            'FirstRegisterDate' => date('Ymd',strtotime($this->visitor->getVehicleVisitor()->firstRegisterDate)),
            'VIN' => $this->visitor->getVehicleVisitor()->vin,
            'EngineNo' => $this->visitor->getVehicleVisitor()->engineNo,
            'ConsultActualValue' => '',
            'VehicleTonnage' => round($this->visitor->getVehicleVisitor()->vehicleTonnage / 1000,2),
            'VehicleQuality' => $this->visitor->getVehicleVisitor()->wholeWeight,
            'VehicleSeat' => $this->visitor->getVehicleVisitor()->vehicleSeat,
            'VehicleExhaust' => $this->visitor->getVehicleVisitor()->vehicleExhaust,
            'Departures' => '',
            'Destinations' => '',
            'PrintVehicleNme' => '',
            'PrintNatureNme' => '',
            'PrintUsageNme' => '',
        ];
    }

    /**
     * 车主信息
     * @return array
     */
    private function setVehicleOwner(): array
    {
        return [
            'VehicleOwnerName' => $this->visitor->getOwnerVisitor()->name,
            'VehicleOwnerType' => JTICEnums::$relationTypeCode[$this->visitor->getOwnerVisitor()->typeCode],
            'VehicleOwnerCertfCls' => JTICEnums::$certificateTypeCode[$this->visitor->getOwnerVisitor()->certificateTypeCode],
            'VehicleOwnerCertfCode' => $this->visitor->getOwnerVisitor()->certificateNo,
            'VehicleOwnerBirth' => $this->getBirthday($this->visitor->getOwnerVisitor()->certificateNo),
            'VehicleOwnerSex' => $this->getGenderByIDcard($this->visitor->getOwnerVisitor()->certificateNo),
        ];
    }

    private function getBirthday($idCard)
    {
        if(strlen($idCard) != 18){
            throw new \Exception("身份证位数不合法");
        }
        return substr($idCard,6,8);
    }

    /**
     * @return
     */
    protected function getNonCarList()
    {
        $list = [];
        /**@var NonCarProductVisitor $value*/
        foreach ($this->visitor->getNonCarInquiryVisitor()->getNonCarList() as $value){
            $list = [
                'ProjectCode' => $value->productCode,
                'InsuredAge' => $this->getAgeFromIdCard($this->visitor->getInsuredVisitor()->certificateNo),
                'EffectiveDate' => date('Ymd',strtotime($this->visitor->biStartData ?: $this->visitor->ciStartData)),
                'ExpireDate' => date('Ymd',strtotime('-1 day',strtotime('+1 year', strtotime($this->visitor->biStartData ?: $this->visitor->ciStartData)))),
            ];
        }
        return $list;
    }
    public function getAgeFromIdCard($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new \Exception("非法的身份证格式"); // 身份证号码必须是18位
        }

        $year = (int)substr($idCard, 6, 4); // 获取出生年份
        return date('Y') - $year + (date('md') < substr($idCard, 10, 4) ? 0 : 1);
    }
    /**
     * 交强险信息
     * @return array
     */
    private function setApplicationTCI():array
    {
        if (!$this->visitor->getCiStartData()) {
            return [];
        }
        return [
            'EffectiveDate' => date('YmdHis',strtotime($this->visitor->getCiStartData())),
            'ExpireDate' => date('YmdHis',strtotime($this->visitor->getCiEndData())),
            'VehicleTax' => [
                'TaxConditionCode' => JTICEnums::$taxTypeCode[$this->visitor->getCarTaxVisitor()->taxTypeCode],
                'TaxPayerName' => $this->visitor->getCarTaxVisitor()->taxpayerName,
                'TaxPayerIdentificationCode' => $this->visitor->getCarTaxVisitor()->taxpayerCertificateNo,
                'TaxDepartment' => $this->visitor->getCarTaxVisitor()->taxDepartment,
                'DocumentNumber' => $this->visitor->getCarTaxVisitor()->taxDocumentNumber,
                'DeductionDueCode' => JTICEnums::$taxReductionReasonCode[$this->visitor->getCarTaxVisitor()->taxReductionReasonCode] ?? '',
                'DeductionDueProportion' => $this->visitor->getCarTaxVisitor()->taxFreeRate,
                'Deduction' => $this->visitor->getCarTaxVisitor()->taxExemption,
                'TaxDocumentDate' => $this->visitor->getCarTaxVisitor()->taxDocumentDate?date('Ymd',strtotime($this->visitor->getCarTaxVisitor()->taxDocumentDate)) : '',
                'TaxPaidAreaCode' => $this->visitor->getCarTaxVisitor()->taxPaidAreaCode,
            ]
        ];
    }

    /**
     * 商业险信息
     * @return array
     * @throws \Exception
     */
    private function setApplicationVCI():array
    {
        if (!$this->visitor->getBiStartData()) {
            return [];
        }

        $coverageList = [];
        $drivingServiceList = [];
        $chargingPostList = [];

        /*** @var PremiumCoverageVisitor  $coverageVisitor */
        foreach ($this->visitor->getCoverageVisitorList() as $coverageVisitor) {

            //交强险
            if ($coverageVisitor->coverageCode == 'C01001') {
                continue;
            }
            $coverageCode = JTICEnums::$coverageCode[$coverageVisitor->coverageCode];
            if (mb_strlen($coverageCode) != 6) {
                throw new \Exception($coverageCode.' 暂不支持');
            }

            $coverage = [
                'CoverageCode' => $coverageCode,
                'CoverageAmount' => $coverageVisitor->amount,
            ];
            //车损保额
            if ($coverageCode == '030006') {
                $coverage['DeductAmount'] = '300';
            }
            //乘客座位险
            if ($coverageCode == '030009') {
                $coverage['PerSeatAmount'] = $coverageVisitor->unitAmount;
            }
            //司机险
            if ($coverageCode == '030001') {
                $coverage['PerSeatAmount'] = $coverageVisitor->amount;
            }
            //修理补偿险
            if ($coverageCode == '033007') {
                $coverage['DayClaimAmount'] = $coverageVisitor->amount;
                $coverage['MaxClaimDays'] = $coverageVisitor->quantity;
            }
            //道路救援
            if ($coverageCode == '033503') {
                $coverage['ServiceTimes'] = $coverageVisitor->serviceTimes;
            }
            //绝对免赔率
            if (in_array($coverageCode,['033507','033508','033509','033510'])) {
                $coverage['AbsoluteDeductRate'] = $coverageVisitor->deductionRate;
            }
            //代为送检
            if ($coverageCode == '033506') {
                $coverage['ServiceTimes'] = $coverageVisitor->serviceTimes;
                $monthDiff = $this->monthDiff($this->visitor->getVehicleVisitor()->firstRegisterDate,$this->visitor->getBiStartData());
                //免过线
                if ($monthDiff < 6*12) {
                    $coverage['ServiceItem'] = '1';
                } else {
                //需过线取送车
                    $coverage['ServiceItem'] = '2';
                }
            }
            //车辆安全检
            if ($coverageCode == '033504') {
                //检测项目代码
                $coverage['CheckItems'] = '1,2,3,4,5,6,7,8,9,10';
                $coverage['ServiceTimes'] = $coverageVisitor->serviceTimes;
            }
            //代驾
            if ($coverageCode == '033505') {
                $drivingServiceList[] = [
                    'DrivingServiceType' => '30',
                    'DrivingServiceTimes' => $coverageVisitor->serviceTimes,
                ];
            }
            //绝对免率
            if (in_array($coverageCode,['033507','033508','033509','033510','033511'])) {
                $drivingServiceList['AbsoluteDeductRate'] = $coverageVisitor->deductionRate;
            }
            $coverageList[] = $coverage;
        }

        /**
         * @var $chargingPileVisitor PremiumChargingPileVisitor
         */
        foreach ($this->visitor->getChargingPileVisitorList() as $chargingPileVisitor) {
            $chargingPostList[] = [
                'ChargingPostCode' => $chargingPileVisitor->chargingPileCode,
                'ChargingPostKind' => JTICEnums::$chargingPileKind[$chargingPileVisitor->chargingPileKind],
                'ChargingPostAddressType' => JTICEnums::$chargingPileAddressType[$chargingPileVisitor->chargingPileAddressType],
            ];
        }

        return [
            'EffectiveDate' => date('YmdHis',strtotime($this->visitor->getBiStartData())),
            'ExpireDate' => date('YmdHis',strtotime($this->visitor->getBiEndData())),
            'ExpectDisc' => $this->visitor->getExtInfoVisitor()->expectedDiscount,
            'CoverageList' => ['CoverageItem' => $coverageList],
            'DrivingServiceList' => ['DrivingServiceItem' => $drivingServiceList],
            'ChargingPostList' => ['ChargingPostItem' => $chargingPostList],
            'SelfPricingCoef' => $this->visitor->getExtInfoVisitor()->selfPricingFactor,//自主定价系数
        ];
    }

    private function getGenderByIDcard($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new \Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard, 16, 1)) % 2;
        return $gender ? '1' : '2';
    }


    /**
     * 相差月份
     * @param $firstRegisterDate
     * @param $startDate
     * @return float|int|mixed|string
     */
    private function monthDiff($firstRegisterDate, $startDate)
    {
        $startDate = date('Y-m-d',strtotime($startDate));
        $firstRegisterDate = explode('-', $firstRegisterDate);

        $startDate = explode('-', $startDate);

        $DYear = $startDate[0] - $firstRegisterDate[0];
        $DMonth = $startDate[1] - $firstRegisterDate[1];
        $DDay = $startDate[2] - $firstRegisterDate[2];

        $monthDiff = $DYear * 12 + $DMonth;

        if ($DDay < 0) {
            $monthDiff -= 1;
        }

        return $monthDiff;
    }
}
